<template>
  <!-- 外协第二步 -->
  <div class="step2 mt-2">
    <div class="top">
      <div class="flexcc left">
        <div class="bold">
          <span>{{ t(`externalAssistance.step2`) }}:</span>
          <span v-if="locale === 'zh-CN'">编辑【{{ store.category.projectName }}】外协单</span>
          <span v-if="locale === 'en'">Edit [{{ store.category.projectName }} ] outsourcing order</span>
        </div>
        <el-button
          type="primary"
          class="ml-2"
          @click="handleAssociatedShip"
        >
          {{ t(`externalAssistance.btn2`) }}
        </el-button>
      </div>
      <div class="right">
        <el-button
          type="primary"
          @click="handleBack"
        >
          {{ t(`externalAssistance.Back`) }}
        </el-button>
        <el-button
          type="primary"
          @click="handleNext"
        >
          {{ t(`externalAssistance.NextStep`) }}
        </el-button>
        <el-button
          type="primary"
          color="#252628"
          @click="handleSave('save')"
        >
          {{ t(`externalAssistance.Save`) }}
        </el-button>
      </div>
    </div>

    <ShippingInfo
      v-if="shippingInfo"
      :data="shippingInfo"
    />

    <div
      class="module mt-2"
      v-if="!shippingInfo && !detailInfo?.shipRepairYardName && !detailInfo?.repairYardCountries && !detailInfo?.repairYardArea"
    >
      {{ t('procurement.step2page.text1') }}
    </div>

    <el-form
      ref="formEl"
      class="mt-3"
      :model="formData"
      :rules="rules"
      label-width="160px"
      hide-required-asterisk
    >
      <!-- 外协声明 -->
      <!-- <div class="module">
        <div class="title">
          {{ t('externalAssistance.step2page.form.l1') }}
        </div>
        <el-form-item
          prop="assistStatement"
          class="mt-2"
        >
          <el-input
            v-model="formData.assistStatement"
            type="textarea"
            :placeholder="t('externalAssistance.step2page.form.p1')"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
      </div> -->

      <div class="module mt-3">
        <div class="title">{{ t('externalAssistance.step2page.form.t2') }}</div>
        <div
          class="con mt-2"
          v-if="[63, 64].includes(store.category.outsourcingProjectId)"
        >
          <div class="grid-3">
            <el-form-item
              prop="harbor"
              :label="t('externalAssistance.step2page.form.l2')"
            >
              <el-input
                v-model="formData.harbor"
                :placeholder="''"
                maxlength="50"
              />
            </el-form-item>
            <el-form-item
              prop="arrivalTime"
              :label="t('externalAssistance.step2page.form.l3')"
            >
              <el-date-picker
                v-model="formData.arrivalTime"
                value-format="X"
                type="date"
                :placeholder="''"
                :disabled-date="disabled_arrivalTime"
              />
            </el-form-item>
            <el-form-item
              prop="departureTime"
              :label="t('externalAssistance.step2page.form.l4')"
            >
              <el-date-picker
                v-model="formData.departureTime"
                value-format="X"
                type="date"
                :placeholder="''"
                :disabled-date="disabled_departureTime"
              />
            </el-form-item>
          </div>
          <div class="grid-3">
            <el-form-item
              prop="agent"
              :label="t('externalAssistance.step2page.form.l5')"
            >
              <el-input
                v-model="formData.agent"
                :placeholder="''"
                maxlength="50"
              />
            </el-form-item>
            <el-form-item
              prop="quoteOrderCurrency"
              :label="t('dockRepair.label3')"
            >
              <el-select
                v-model="formData.quoteOrderCurrency"
                class="wp-100"
                :placeholder="t('select_p')"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dictData['currency']"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item
              prop="requestDescription"
              :label="t('externalAssistance.step2page.form.l6')"
            >
              <el-input
                v-model="formData.requestDescription"
                type="textarea"
                :placeholder="''"
                maxlength="500"
              />
            </el-form-item>
          </div>
        </div>

        <div
          class="con mt-2"
          v-if="[65].includes(store.category.outsourcingProjectId)"
        >
          <div class="grid-4">
            <el-form-item
              prop="servicePersonCount"
              :label="t('externalAssistance.step2page.form.l7')"
            >
              <el-input
                v-model="formData.servicePersonCount"
                :placeholder="''"
                maxlength="50"
              />
            </el-form-item>
            <el-form-item
              prop="serviceLocation"
              :label="t('externalAssistance.step2page.form.l8')"
            >
              <el-input
                v-model="formData.serviceLocation"
                :placeholder="''"
                maxlength="50"
              />
            </el-form-item>
            <el-form-item
              prop="serviceTime"
              :label="t('externalAssistance.step2page.form.l9')"
            >
              <el-date-picker
                v-model="formData.serviceTime"
                value-format="X"
                type="date"
                placeholder=" "
              />
            </el-form-item>
            <el-form-item
              prop="serviceDayCount"
              :label="t('externalAssistance.step2page.form.l10')"
            >
              <el-input
                v-model="formData.serviceDayCount"
                :placeholder="''"
                maxlength="50"
              />
            </el-form-item>
          </div>
          <div class="grid-4">
            <el-form-item
              prop="quoteOrderCurrency"
              :label="t('dockRepair.label3')"
            >
              <el-select
                v-model="formData.quoteOrderCurrency"
                class="wp-100"
                :placeholder="t('select_p')"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dictData['currency']"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item
              prop="requestDescription"
              :label="t('externalAssistance.step2page.form.l6')"
            >
              <el-input
                v-model="formData.requestDescription"
                type="textarea"
                :placeholder="''"
                maxlength="500"
              />
            </el-form-item>
          </div>
        </div>

        <div
          class="con mt-2"
          v-if="[66].includes(store.category.outsourcingProjectId)"
        >
          <div class="grid-3">
            <el-form-item
              prop="harbor"
              :label="t('externalAssistance.step2page.form.l2')"
            >
              <el-input
                v-model="formData.harbor"
                :placeholder="''"
                maxlength="50"
              />
            </el-form-item>
            <el-form-item
              prop="arrivalTime"
              :label="t('externalAssistance.step2page.form.l3')"
            >
              <el-date-picker
                v-model="formData.arrivalTime"
                value-format="X"
                type="date"
                :placeholder="''"
                :disabled-date="disabled_arrivalTime"
              />
            </el-form-item>
            <el-form-item
              prop="departureTime"
              :label="t('externalAssistance.step2page.form.l4')"
            >
              <el-date-picker
                v-model="formData.departureTime"
                value-format="X"
                type="date"
                :placeholder="''"
                :disabled-date="disabled_departureTime"
              />
            </el-form-item>
          </div>
          <div class="grid-3">
            <el-form-item
              prop="quoteOrderCurrency"
              :label="t('dockRepair.label3')"
            >
              <el-select
                v-model="formData.quoteOrderCurrency"
                class="wp-100"
                :placeholder="t('select_p')"
                filterable
                clearable
              >
                <el-option
                  v-for="item in dictData['currency']"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item
              prop="requestDescription"
              :label="t('externalAssistance.step2page.form.l6')"
            >
              <el-input
                v-model="formData.requestDescription"
                type="textarea"
                :placeholder="''"
                maxlength="500"
              />
            </el-form-item>
          </div>
        </div>
      </div>

      <div class="module mt-3">
        <div class="title">{{ t('procurement.step2page.form.l2') }}</div>
        <el-form-item
          class="mt-2"
          label-width="0"
        >
          <el-cascader
            ref="cascaderRef"
            v-model="category"
            class="wp-100"
            filterable
            clearable
            :options="secondLevelOptions"
            :props="{ value: 'outsourcingProjectId', label: 'projectName', children: 'outsourcingProjectWebVoList' }"
            @change="handleChange"
          />
        </el-form-item>
      </div>
    </el-form>

    <div class="list mt-2">
      <!-- <div class="group flexsc"> -->
      <!-- <div class="mr-4" v-if="locale === 'zh-CN'">已选 1 项</div>
        <div class="mr-4" v-if="locale === 'en'">1 item selected</div> -->

      <!-- 外协项目 -->
      <!-- <el-button
          type="primary"
          @click="handleAdd"
        >
          +{{ t(`externalAssistance.btn1`) }}
        </el-button>
      </div> -->

      <div class="table mt-2">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2
              :columns="columns"
              :data="tableData"
              :width="width"
              :height="height"
              fixed
            >
              <template #empty>
                <div class="flexcc-col mt-4">
                  <div>
                    <img
                      src="@/assets/img/icon_wushuju.png"
                      alt=""
                    />
                  </div>
                  <div class="mt-2">
                    {{ t('externalAssistance.noDataText') }}
                  </div>
                  <el-button
                    type="primary"
                    @click="handleAddOne(0)"
                    class="mt-2"
                  >
                    +{{ t(`externalAssistance.btn1`) }}
                  </el-button>
                </div>
              </template>
            </el-table-v2>
          </template>
        </el-auto-resizer>
      </div>
    </div>

    <div class="file-list mt-5">
      <Uploads
        ref="UploadsRef"
        @change="fileChange"
        :tip="t('Uploads.t2')"
      />
    </div>

    <!-- 设备项目录入 -->
    <ProjectAdd
      v-if="dialogProjectAdd"
      :visible="dialogProjectAdd"
      :editRow="editRow"
      :checkedRow="checkedRow"
      @close="dialogProjectAdd = false"
      @getDetail="getDetail(false)"
    />

    <!-- 关联船舶 -->
    <AssociatedShip
      v-if="dialogAssociatedShip"
      :visible="dialogAssociatedShip"
      :shippingId="shippingId"
      :enterpriseInfo="enterpriseInfo"
      @getDetail="getDetail(false)"
      @close="dialogAssociatedShip = false"
    />

    <!-- 保存确认 -->
    <Confirm
      v-if="dialogConfirmSave"
      :visible="dialogConfirmSave"
      :title="t('externalAssistance.step2page.Confirm.title')"
      :text="t('externalAssistance.step2page.Confirm.text')"
      :cancelText="t('donNotSaveText')"
      @cancel="handleDelete"
      @close="dialogConfirmSave = false"
      @confirm=";(dialogConfirmSave = false), handleSave('back')"
    />

    <!-- 保存后设置可查看人员 -->
    <ConfigPerson
      v-if="dialogConfigPerson"
      :visible="dialogConfigPerson"
      :saveType="saveType"
      :canViewPerson="canViewPerson"
      @close="dialogConfigPersonClose"
    />
  </div>
</template>

<script setup lang="jsx">
import { ref, unref, watch, computed, onBeforeMount, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import useExternalAssistance from '@/stores/externalAssistance.js'
import { detailApi, deleteApi, deleteDetailApi, editApi, editOrderDetailApi, batchUpdateTypeApi } from '@/service/externalAssistance'
import { uploads } from '@/service/common.js'
import useLogin from '@/stores/login.js'
import { debounce } from 'lodash'

import AssociatedShip from './AssociatedShip.vue' // 关联船舶
import Confirm from '@/components/Confirm.vue' // 确认框
import ConfigPerson from './ConfigPerson.vue' // 设置可查看人员

import ProjectAdd from './ProjectAdd.vue' // 项目录入
import Uploads from '@/components/Uploads.vue'

import useDict from '@/hooks/useDict'
const { dictData, getDictData, getDictLabel } = useDict()

const router = useRouter()
const route = useRoute()
const storeLogin = useLogin()

const { t, locale } = useI18n()

onMounted(() => {
  init()
})
watch(locale, (n) => {
  init()
})

const store = useExternalAssistance()
const { next, back, setOrderInfo } = store

const category = ref([])
// 二级类别
const secondLevelOptions = computed(() => {
  return store.category.outsourcingProjectWebVoList
})
const cascaderRef = ref() // 级联ref
const projectName = ref('') // 三级
const handleChange = (val) => {
  projectName.value = cascaderRef.value.getCheckedNodes()[0].label
  batchUpdateTypeApi({
    orderId: store.orderInfo.id,
    projectId: val[val.length - 1]
  }).then(() => {
    getDetail(false)
  })
}

// 到达时间不可大于离岗时间
const disabled_arrivalTime = (val) => {
  if (!formData.value.departureTime) {
    return val.getTime() < Date.now() - 8.64e7 // 今天之前的不可选
  }
  return val.getTime() > formData.value.departureTime * 1000
}

// 离岗时间不可小于到达时间
const disabled_departureTime = (val) => {
  if (!formData.value.arrivalTime) {
    return val.getTime() < Date.now() - 8.64e7 // 今天之前的不可选
  }
  return val.getTime() < formData.value.arrivalTime * 1000
}

// 返回时
const handleBack = () => {
  dialogConfirmSave.value = true
}

// 保存确认
const dialogConfirmSave = ref(false)

// 删除外协单
const handleDelete = () => {
  deleteApi(store.orderInfo.id).then(({ msg }) => {
    dialogConfirmSave.value = false
    back()
    router.replace({
      path: route.path
    })
  })
}

// 保存后设置可查看人员
const dialogConfigPerson = ref(false)
const canViewPerson = ref([])
const dialogConfigPersonClose = () => {
  dialogConfigPerson.value = false
  if (saveType.value === 'save') {
    getDetail()
  }
}

// 下一步
const handleNext = () => {
  handleSave('next')
}

// 保存
const saveType = ref('save') // save保存  next下一步 back上一步
const handleSave = (type = 'save') => {
  if (!formEl.value) return

  const { assistOrderName, _assistOrderName } = store.orderInfo

  const params = {
    ...detailInfo.value,
    ...formData.value
  }

  if (!_assistOrderName) {
    ElMessage.warning(t('externalAssistance.step2page.w1'))
    return
  }
  params.assistOrderName = _assistOrderName

  formEl.value.validate(async (valid, fields) => {
    if (valid) {
      params.urlList = await handleUpload()

      editApi(params).then(() => {
        dialogConfigPerson.value = true
        saveType.value = type
        getDetail()
      })
    }
  })
}

// 关联船舶
const dialogAssociatedShip = ref(false)
const handleAssociatedShip = () => {
  dialogAssociatedShip.value = true
}

// 表单
const formEl = ref(null)
const formData = ref({})
const rules = reactive({
  // assistStatement: [{ required: true, message: t('externalAssistance.step2page.r1'), trigger: 'blur' }],
  quoteOrderCurrency: [{ required: true, message: t('dockRepair.step2page.r5'), trigger: 'blur' }],
  harbor: [{ required: true, message: '', trigger: 'blur' }],
  arrivalTime: [{ required: true, message: '', trigger: 'blur' }],
  departureTime: [{ required: true, message: '', trigger: 'blur' }],
  agent: [{ required: true, message: '', trigger: 'blur' }],
  requestDescription: [{ required: true, message: '', trigger: 'blur' }],
  servicePersonCount: [{ required: true, message: '', trigger: 'blur' }],
  serviceLocation: [{ required: true, message: '', trigger: 'blur' }],
  serviceTime: [{ required: true, message: '', trigger: 'blur' }],
  serviceDayCount: [{ required: true, message: '', trigger: 'blur' }]
})

// 项目录入
const dialogProjectAdd = ref(false)
watch(dialogProjectAdd, (n) => {
  if (!n) {
    editRow.value = null
  }
})

// 复选框 组件
const SelectionCell = ({ value, intermediate = false, onChange }) => {
  return (
    <ElCheckbox
      onChange={onChange}
      modelValue={value}
      indeterminate={intermediate}
    />
  )
}

// 正在编辑的行
const editRow = ref(null)

// 勾选的 行
const checkedRow = ref(null)

// 获取列
const columns = ref([])
const getColumns = () => {
  const setRef = (el) => {
    if (el) {
      el.focus?.()
    }
  }
  const setEditingClassName = (flag = true) => {
    return { 'table-v2-inline-editing-trigger': flag }
  }

  // 保存
  const handleRowSave = debounce(
    (rowData) => {
      editOrderDetailApi(rowData).then(({ msg, data }) => {
        ElMessage.success(msg)
        rowData.isSave = true
        rowData.editingKey = null
        rowData.id = data
      })
    },
    500,
    {
      leading: true, // 延长开始后调用
      trailing: false // 延长结束前调用
    }
  )

  // 回车保存
  const handleEnterSave = (e, rowData) => {
    if (['Enter', 'NumpadEnter'].includes(e.code)) {
      handleRowSave(rowData)
    }
  }

  const arr_63 = [
    {
      title: t('externalAssistance.category1Col.t1'),
      key: 'assistName',
      dataKey: 'assistName',
      width: 300,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'assistName') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.assistName}
              placeholder=" "
              maxlength={50}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'assistName'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.assistName}
          </div>
        )
      }
    },
    {
      title: t('externalAssistance.category1Col.tit4'),
      key: 'assistSpec',
      dataKey: 'assistSpec',
      width: 300,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'assistSpec') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.assistSpec}
              placeholder=" "
              maxlength={50}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'assistSpec'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.assistSpec}
          </div>
        )
      }
    },
    {
      title: t('procurement.col.t3'),
      key: 'unit',
      dataKey: 'unit',
      width: 200,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'unit') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.unit}
              placeholder={t('procurement.ProjectAdd.p7-2')}
              maxlength={50}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'unit'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.unit}
          </div>
        )
      }
    },
    {
      title: t('procurement.category4Col.tit5'),
      key: 'requireCount',
      dataKey: 'requireCount',
      width: 200,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'requireCount') {
          return (
            <el-input-number
              ref={setRef}
              v-model={rowData.requireCount}
              placeholder=" "
              controls={false}
              style="width: 100%"
              max={999999999}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'requireCount'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.requireCount}
          </div>
        )
      }
    }
  ]
  const obj = {
    63: arr_63,
    64: arr_63,
    65: [
      {
        title: t('externalAssistance.category3Col.t1'),
        key: 'assistName',
        dataKey: 'assistName',
        width: 600,
        cellRenderer: ({ rowData }) => {
          if (rowData.editingKey === 'assistName') {
            return (
              <el-input
                ref={setRef}
                v-model={rowData.assistName}
                placeholder=" "
                maxlength={50}
                onBlur={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }

          const onEnterEditMode = () => {
            rowData.editingKey = 'assistName'
          }

          return (
            <div
              class={setEditingClassName()}
              onClick={onEnterEditMode}
            >
              {rowData.assistName}
            </div>
          )
        }
      },
      {
        title: t('externalAssistance.category3Col.t2'),
        key: 'unit',
        dataKey: 'unit',
        width: 200,
        cellRenderer: ({ rowData }) => {
          if (rowData.editingKey === 'unit') {
            return (
              <el-input
                ref={setRef}
                v-model={rowData.unit}
                placeholder={t('procurement.ProjectAdd.p7-2')}
                maxlength={50}
                onBlur={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }

          const onEnterEditMode = () => {
            rowData.editingKey = 'unit'
          }

          return (
            <div
              class={setEditingClassName()}
              onClick={onEnterEditMode}
            >
              {rowData.unit}
            </div>
          )
        }
      },
      {
        title: t('procurement.category4Col.tit5'),
        key: 'requireCount',
        dataKey: 'requireCount',
        width: 200,
        cellRenderer: ({ rowData }) => {
          if (rowData.editingKey === 'requireCount') {
            return (
              <el-input-number
                ref={setRef}
                v-model={rowData.requireCount}
                placeholder=" "
                controls={false}
                style="width: 100%"
                max={999999999}
                onBlur={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }

          const onEnterEditMode = () => {
            rowData.editingKey = 'requireCount'
          }

          return (
            <div
              class={setEditingClassName()}
              onClick={onEnterEditMode}
            >
              {rowData.requireCount}
            </div>
          )
        }
      }
    ],
    66: [
      {
        title: t('externalAssistance.category3Col.t1'),
        key: 'assistName',
        dataKey: 'assistName',
        width: 600,
        cellRenderer: ({ rowData }) => {
          if (rowData.editingKey === 'assistName') {
            return (
              <el-input
                ref={setRef}
                v-model={rowData.assistName}
                placeholder=" "
                maxlength={50}
                onBlur={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }

          const onEnterEditMode = () => {
            rowData.editingKey = 'assistName'
          }

          return (
            <div
              class={setEditingClassName()}
              onClick={onEnterEditMode}
            >
              {rowData.assistName}
            </div>
          )
        }
      },
      {
        title: t('procurement.col.t3'),
        key: 'unit',
        dataKey: 'unit',
        width: 200,
        cellRenderer: ({ rowData }) => {
          if (rowData.editingKey === 'unit') {
            return (
              <el-input
                ref={setRef}
                v-model={rowData.unit}
                placeholder={t('procurement.ProjectAdd.p7-2')}
                maxlength={50}
                onBlur={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }

          const onEnterEditMode = () => {
            rowData.editingKey = 'unit'
          }

          return (
            <div
              class={setEditingClassName()}
              onClick={onEnterEditMode}
            >
              {rowData.unit}
            </div>
          )
        }
      },
      {
        title: t('procurement.category4Col.tit5'),
        key: 'requireCount',
        dataKey: 'requireCount',
        width: 200,
        cellRenderer: ({ rowData }) => {
          if (rowData.editingKey === 'requireCount') {
            return (
              <el-input-number
                ref={setRef}
                v-model={rowData.requireCount}
                placeholder=" "
                controls={false}
                style="width: 100%"
                max={999999999}
                onBlur={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }

          const onEnterEditMode = () => {
            rowData.editingKey = 'requireCount'
          }

          return (
            <div
              class={setEditingClassName()}
              onClick={onEnterEditMode}
            >
              {rowData.requireCount}
            </div>
          )
        }
      }
    ]
  }
  columns.value = [
    // {
    //   key: 'selection',
    //   width: 50,
    //   fixed: 'left',
    //   align: 'center',
    //   cellRenderer: ({ rowData }) => {
    //     const _data = unref(tableData.value)
    //     const onChange = (value) => {
    //       _data.forEach((row) => (row.checked = false))
    //       rowData.checked = value
    //       checkedRow.value = value ? rowData : null
    //     }

    //     return (
    //       <SelectionCell
    //         value={rowData.checked}
    //         onChange={onChange}
    //       />
    //     )
    //   }
    // },
    {
      title: t('indexNumber'),
      key: 'index',
      dataKey: 'index',
      width: 50,
      cellRenderer: ({ rowIndex }) => {
        return rowIndex + 1
      }
    },
    ...(obj[store.category.outsourcingProjectId] || []),
    {
      title: t('externalAssistance.operation'), // 操作
      width: 150,
      fixed: 'right',
      cellRenderer: ({ rowData, rowIndex }) => {
        const _data = unref(tableData.value)

        // 删除
        const handleDelete = (value) => {
          if (!rowData.id) {
            _data.splice(rowIndex, 1)
            return
          }
          deleteDetailApi({
            id: rowData.id
          }).then(({ msg }) => {
            ElMessage.success(msg)
            _data.splice(rowIndex, 1)
          })
        }
        return (
          <>
            <el-popconfirm
              title={t('popconfirm_del')}
              v-slots={{
                reference: () => (
                  <img
                    src={new URL('@/assets/img/icon_shanchu.png', import.meta.url)}
                    height="22"
                    class="mr-2"
                  />
                )
              }}
              onConfirm={handleDelete}
            ></el-popconfirm>

            <el-icon onClick={() => handleAddOne(rowIndex)}>
              <Plus />
            </el-icon>
          </>
        )
      }
    }
  ]
}
// 表格数据
const tableData = ref([])

// 详情
const shippingInfo = ref(null) // 船舶信息
const shippingId = ref(null) // 船舶id
const enterpriseInfo = ref(null) // 修船厂信息
const detailInfo = ref(null)
const getDetail = (isUpdate = true) => {
  detailApi(store.orderInfo.id).then(({ data }) => {
    detailInfo.value = data
    data._assistOrderName = data.assistOrderName

    const { shcwShippingVo, shippingId: sid, assistStatement, quoteOrderCurrency, shipRepairYardName, repairYardCountries, repairYardArea, assistOrderDetailEditVoList, canViewPerson: person, urlList, harbor, arrivalTime, departureTime, agent, requestDescription, servicePersonCount, serviceLocation, serviceTime, serviceDayCount } = data

    if (shcwShippingVo) {
      shippingInfo.value = shcwShippingVo
    }
    if (assistOrderDetailEditVoList?.length) {
      const { mediumId, outsourcingProjectId } = assistOrderDetailEditVoList[0]
      category.value = mediumId === outsourcingProjectId ? [outsourcingProjectId] : [mediumId, outsourcingProjectId]
      assistOrderDetailEditVoList.forEach((item) => {
        item.isSave = true
        if (item.constructionLocation) {
          item.constructionLocationDisplay = dictData.value.construction_location.find((d) => d.dictValue === item.constructionLocation)?.dictLabel
        }
      })
      tableData.value = assistOrderDetailEditVoList
    }
    shippingId.value = sid
    enterpriseInfo.value = {
      enterpriseName: shipRepairYardName,
      enterpriseCountry: repairYardCountries,
      enterpriseAre: repairYardArea
    }

    let qc = ''
    if (['中国', 'China'].includes(storeLogin.userInfo.enterpriseCountry)) {
      qc = 'currency_0'
    } else {
      qc = 'currency_1'
    }

    if (isUpdate) {
      formData.value = {
        assistStatement,
        quoteOrderCurrency: quoteOrderCurrency || qc,
        harbor,
        arrivalTime,
        departureTime,
        agent,
        requestDescription,
        servicePersonCount,
        serviceLocation,
        serviceTime,
        serviceDayCount
      }
      setOrderInfo(data)
    }

    if (person) canViewPerson.value = person

    if (urlList) {
      fileList.value = urlList.map((item) => {
        return {
          name: item.slice(item.lastIndexOf('/') + 1),
          url: item
        }
      })
    }

    UploadsRef.value.setFileList(fileList.value)
  })
}

// 添加外协项目
const handleAdd = () => {
  dialogProjectAdd.value = true
}

// 加一行
const handleAddOne = (index) => {
  // if (!category.value.length) {
  //   ElMessage.warning(t('procurement.step2page.form.r2'))
  //   return
  // }
  tableData.value.splice(index + 1, 0, {
    projectName: projectName.value || cascaderRef.value?.getCheckedNodes()[0]?.label,
    assistOrderId: store.orderInfo.id,
    largeId: store.category.outsourcingProjectId,
    mediumId: category.value[0],
    outsourcingProjectId: category.value[category.value.length - 1]
  })

  // console.log(tableData.value, '==')
}

// 文件列表
const fileList = ref([])
const fileChange = (val) => {
  fileList.value = val
}
const UploadsRef = ref(null)
const handleUpload = () => {
  return new Promise((resolve, reject) => {
    const newList = fileList.value.filter((item) => item.raw)
    const oldList = fileList.value.filter((item) => !item.raw).map((item) => item.url)

    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls }) => {
        const resultFile = urls.split(',')
        fileList.value = resultFile.map((item) => {
          return {
            name: item.slice(item.lastIndexOf('/') + 1),
            url: item
          }
        })
        UploadsRef.value.setFileList(fileList.value)
        resolve([...oldList, ...resultFile])
      })
    } else {
      resolve(oldList)
    }
  })
}

// init
const init = async () => {
  getDictData('currency')
  getDictData('ships_type')
  getDictData('classification_society')
  await getDictData('construction_location')
  getColumns()
  getDetail()
}
</script>

<style scoped lang="scss">
.step2 {
  padding-bottom: 36px;
  .el-button {
    min-width: 150px;
  }
  .top {
    display: grid;
    grid-template-columns: repeat(2, auto);
    gap: 0px;
    justify-content: space-between;
  }

  .grid {
    display: grid;
    grid-template-columns: repeat(3, 370px) 105px;
    gap: 15px;
  }

  :deep(.el-date-editor) {
    width: 100%;
    .el-input__wrapper {
      width: 100%;
    }
  }

  :deep(.el-form-item__label) {
    line-height: 1;
    align-items: center;
  }

  .module {
    background: #fff;
    padding: 24px;
    .title {
      border-bottom: #252628 2px solid;
      color: #252628;
      padding-bottom: 10px;
    }
  }

  .list {
    background: #fff;
    padding: 24px 24px 0;

    .table {
      border-top: 2px solid #252628;
      height: 700px;

      :deep(.table-v2-inline-editing-trigger) {
        border: 1px transparent dotted;
        padding: 4px;
        min-height: 26px;
        min-width: 100%;
        cursor: text;
        border-radius: 3px;
      }

      :deep(.table-v2-inline-editing-trigger:hover) {
        border-color: var(--el-color-primary);
      }

      :deep(.el-table-v2__header-cell) {
        background: #f0f3f8;
        color: #252628;
      }
    }
  }
}
</style>
